package com.pzl.service.impl;

import com.pzl.entity.User;
import com.pzl.mapper.RoleMapper;
import com.pzl.mapper.UserMapper;
import com.pzl.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * UserService class
 *
 * @Author panzhenglei
 * @Date 2019/6/8 9:37 AM
 */

@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;

    private RoleMapper roleMapper;

    /**
     * 搜索全部User
     * @return
     * @throws Exception
     */
    @Override
    public List<User> findAll() throws Exception {
        List<User> users = userMapper.findAll();
        return users;
    }

    /**
     * 新建User
     * @param user
     * @param roleIds
     * @return
     */
    @Override
    public Long save(User user,Long[] roleIds) {

        Long i = userMapper.save(user);

        System.out.println(i);

        Long id = user.getId();

        System.out.println(id);

        /*for (Long roleId : roleIds) {

            userMapper.saveUserRole(id,roleId);

        }*/

        if (roleIds != null&&roleIds.length != 0){

            for (Long roleId : roleIds) {

                userMapper.saveUserRole(user,roleId);

            }
        }

        if (i>0){
            return 1L;
        }
        return 0L;

    }

    /**
     * 根据id搜索User
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public User findOne(Long id) throws Exception {

        User one = userMapper.findOne(id);

        return one;
    }


    /**
     * 新建User
     * @param user
     * @param roleIds
     * @return
     */
    @Override
    public Long update(User user, Long[] roleIds) {

        int i = userMapper.update(user);

        userMapper.deleteURById(user.getId());

        for (Long roleId : roleIds) {
            userMapper.saveUserRole(user,roleId);
        }

        if (i>0){
            return 1L;
        }
        return 0L;
    }

    @Override
    public Long delete(Long id) {


        int j = userMapper.deleteURById(id);

        int i = userMapper.deleteById(id);

        if (i>0&&j>0){
            return 1L;
        }
        return 0L;

    }
}
